
import ProForm, { ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { useUpdateEffect } from '@umijs/hooks';
import { Button, Drawer } from 'antd';
import { Spin, List, Segmented } from 'antd';
import { getAgentRootPath, getDirectory } from '../service';
import { useRequestHandle } from '@/utils/utils';
import { CloudServerOutlined, FolderFilled } from '@ant-design/icons';
import { useState } from 'react';
import styles from './index.less';
import { Input } from 'antd';
import { message } from 'antd';
import { useRef } from 'react';
const SaveForm = (props) => {
  const { modalVisible, onCancel, onSubmit, loading, record, id } = props;

  const [rootPath, setRootPath] = useState([]);
  const [hoverRootPath, setHoverRootPath] = useState("");
  const [directoryList, setDirectoryList] = useState([]);
  const [lastDirectory, setLastDirectory] = useState([]);
  const [hoverDirectory, setHoverDirectory] = useState("");
  const [searchValue, setSearchValue] = useState("");
  const formRef = useRef();
  const getAgentRootPathRequest = useRequestHandle(getAgentRootPath, (data) => {

    const tmp = data.map(item => {
      return {
        label: item,
        value: item,
        icon: <CloudServerOutlined />,
      }
    });
    if (!record.id) {
      setHoverRootPath(tmp[0].value);
      setHoverDirectory(tmp[0].value);
    }
    setRootPath(tmp)
  })
  const getDirectoryRequest = useRequestHandle(getDirectory, (data) => {

    setDirectoryList(data);
  })
  useUpdateEffect(() => {
    if (modalVisible) {
      getAgentRootPathRequest.run({ id })
    }
  }, [modalVisible])
  useUpdateEffect(() => {
    if (record.id) {
      const pathArray = record.rootPath.split("\\");
      setHoverRootPath(`${pathArray[0]}\\`);
      let hoverDir = "";
      for (let i = 0; i < pathArray.length - 1; i++) {
        hoverDir += `${pathArray[i]}\\`;
      }
      const lastDir = [];
      if (pathArray.length > 2) {
        for (let i = 0; i < pathArray.length - 2; i++) {
          lastDir.push(pathArray[i]);
        }
      }
      else {
        lastDir.push(pathArray[0]);
      }

      setLastDirectory(lastDir);
      setHoverDirectory(hoverDir);
    }
  }, [record])
  useUpdateEffect(() => {
    if (hoverDirectory) {
      getDirectoryRequest.run({ id, path: hoverDirectory })
    }
  }, [hoverDirectory]);
  let tmpDirectoryList = directoryList.filter(item => item.type === 2);
  if (searchValue) {
    tmpDirectoryList = tmpDirectoryList.filter(item => item.path.indexOf(searchValue) !== -1)
  }
  return (
    <Drawer
      destroyOnClose
      title={record.id ? '修改配置' : '添加配置'}
      open={modalVisible}
      // onCancel={() => onCancel()}
      onClose={() => onCancel()}
      width={600}
      footer={null}
    >
      <Spin tip="正在处理..." spinning={loading || getDirectoryRequest.loading}>
        <ProForm
          onFinish={async (value) => {
            const params = value;
            if (record.id) {
              params.id = record.id;
            }
            await onSubmit(params);
          }}
          formRef={formRef}
          initialValues={{ ...record }}
        >
          <ProForm.Group>
            <ProFormText
              name="serverName"
              label="服务名称"
              fieldProps={{
                allowClear: true,
              }}
              placeholder="请输入服务名称"
              rules={[{ required: true, message: '请输入服务名称！' }]}
            />

          </ProForm.Group>

          <ProFormTextArea
            name="remark"
            label="备注"
            fieldProps={{
              allowClear: true,
            }}
            placeholder="请输入备注"
            rules={[{ required: false, message: '请输入备注' }]} />
          <ProFormText
            name="iisName"
            label="IIS站点名称"
            extra="请务必填写正确iis中的站点名称，用于启停服务"
            fieldProps={{
              allowClear: true,

            }}
            placeholder="请输入IIS站点名称"
            rules={[{ required: true, message: '请输入IIS站点名称' }]}
          />
          <ProFormText
            name="rootPath"
            label="服务目录"
            fieldProps={{
              allowClear: true,
              disabled: true
            }}
            placeholder="请选择服务目录"
            rules={[{ required: true, message: '请选择服务目录' }]}
          />
          <div style={{ marginBottom: "12px" }}>选择路径：</div>
          <Segmented
            style={{ marginBottom: "12px" }}
            options={rootPath}
            value={hoverRootPath}
            defaultValue={hoverRootPath}
            onChange={(value) => {
              setHoverRootPath(value);
              setHoverDirectory(value);
            }}
          />
          <Input value={searchValue} onChange={
            (e) => {
              setSearchValue(e.target.value)
            }
          } style={{ marginBottom: "12px" }} placeholder='请输入关键字' />
          <List
            style={{ marginBottom: "12px" }}
            size="small"
            bordered
            dataSource={lastDirectory && lastDirectory.length >= 1 ? [{ path: "..", type: 2 }, ...tmpDirectoryList] : tmpDirectoryList}
            renderItem={(item) => <List.Item>
              <div className={styles.directory}>
                <span onClick={() => {
                  if (item.path === "..") {
                    const lastPath = lastDirectory[lastDirectory.length - 1];
                    const newLastDirectory = lastDirectory.slice(0, lastDirectory.length - 1);
                    setLastDirectory(newLastDirectory);
                    setHoverDirectory(lastPath);
                  }
                  else {
                    if (item.canRead && item.canWrite) {
                      const newLastDirectory = lastDirectory;
                      newLastDirectory.push(hoverDirectory);
                      setLastDirectory(newLastDirectory);
                      setHoverDirectory(item.path);
                    }
                    else {
                      message.error("无读取或者写入权限")
                    }

                  }

                }}> <FolderFilled style={{ color: "#54aeff", marginRight: "4px" }} color='#54aeff' />
                  {item.path === ".." ? "" : <span>{item.path}
                    <span style={item.canRead ? { color: "green", marginLeft: "10px", fontSize: "12px" } : { color: "red", marginLeft: "10px", fontSize: "12px" }}>读</span>
                    <span style={item.canWrite ? { color: "green", marginLeft: "10px", fontSize: "12px" } : { color: "red", marginLeft: "10px", fontSize: "12px" }}>写</span>
                  </span>}
                  <span style={{ fontSize: "12px", color: "#0083e3" }}>
                    {item.path === ".." ? <>返回上一级<span style={{ marginLeft: "10px" }}>{lastDirectory[lastDirectory.length - 1]}</span></> : ""}</span>
                </span>

                {item.path !== ".." && item.canRead && item.canWrite ? <Button
                  onClick={() => { formRef.current.setFieldValue("rootPath", item.path) }}
                  size='small' style={{ float: "right" }}>设为根目录</Button> : null}
              </div></List.Item>}
          />
        </ProForm>
      </Spin>
    </Drawer>
  );
};

export default SaveForm;
